package service

import (
	"github.com/pkg/errors"
	"github.com/spf13/cast"
	"nft-server/dao"
	"nft-server/model"
)

func GetAssetRelationBySubCollectionIndex(collectionIndex string, userId int, subCollectionIndex int) ([]*model.AssetRelation, error) {
	assetRelations, err := dao.GetAssetRelationDao().GetAssetRelationByCollectionId(collectionIndex, userId, subCollectionIndex)
	if err != nil {
		return nil, errors.Errorf("GetAssetRelation error: %v", err)
	}
	return assetRelations, nil
}
func GetAssetOwner(collectionIndex, tokenId string) (*model.AssetRelation, error) {
	assetRelation, err := dao.GetAssetRelationDao().GetAssetOwner(collectionIndex, tokenId)
	if err != nil {
		return nil, errors.Errorf("GetAssetRelationByAssetId error: %v", err)
	}
	return assetRelation, nil
}

func UpdateAssetRelation(collectionIndex, tokenId string, userId int) error {
	assetRelation, err := GetAssetOwner(collectionIndex, tokenId)
	if err != nil {
		return errors.Errorf("GetAssetRelationDao error: %v", err)
	}
	assetRelation.UserId = userId
	err = dao.GetAssetRelationDao().UpdateAssetRelation(assetRelation)
	if err != nil {
		return errors.Errorf("UpdateAssetRelation error: %v", err)
	}
	return nil
}

func DeleteAssetRelation(collectionIndex, tokenId string, userId int) error {
	err := dao.GetAssetRelationDao().DeleteAssetRelation(collectionIndex, tokenId, userId)
	if err != nil {
		return errors.Errorf("DeleteAssetRelation error: %v", err)
	}
	return nil
}

func CreateAssetRelation(collectionIndex string, subCollectionIndex int, startTokenId string, userId int, tokenIdAmount int) error {
	tmpTokenId := cast.ToInt(startTokenId)
	assetRelations := make([]*model.AssetRelation, tokenIdAmount)
	for tokenId := tmpTokenId; tokenId < tmpTokenId+tokenIdAmount; tokenId++ {
		assetRelation := new(model.AssetRelation)
		assetRelation.SubCollectionIndex = subCollectionIndex
		assetRelation.CollectionIndex = collectionIndex
		assetRelation.TokenId = cast.ToString(tokenId)
		assetRelation.UserId = userId
		relationIndex := tokenId - tmpTokenId
		if relationIndex >= 0 && relationIndex < tokenIdAmount {
			assetRelations[relationIndex] = assetRelation
		}
	}
	_, err := dao.GetAssetRelationDao().InsertMultiAssetRelation(assetRelations)
	if err != nil {
		return errors.Errorf("InsertMultiAssetRelation error: %v", err)
	}
	return nil
}

func GetAssetRelationByCollectionId(collectionIndex string, userId int, subCollectionIndex int) ([]*model.AssetRelation, error) {
	collectionRelationAssets, err := dao.GetAssetRelationDao().GetAssetRelationByCollectionId(collectionIndex, userId, subCollectionIndex)
	if err != nil {
		return nil, errors.Errorf("GetAssetRelationByCollectionId error: %v", err)
	}
	return collectionRelationAssets, nil
}
